import re
from xml.dom import minidom
from xml.parsers.expat import ExpatError

def replaceTag( value, tagA, tagB ):
    """ Replaces tagA with tagB in value """
    
    value = re.sub( "<%s.*?>" % tagA, "<%s>" % tagB, value )
    return re.sub( "</%s>" % tagA, "</%s>" % tagB, value )        


def removeTag( value, tag ):
    """ Removes the specified tag (Does not remove innerHTML) """
    
    value = re.sub( "<%s.*?>" % tag, "", value )
    return re.sub( "</%s>" % tag, "", value )

def html2rml( value ):
    """ Best attempt at converting HTML to RML """
        
    value = re.sub("&", "&amp;", value) #FIXME - Might already be specified as &amp; !!!
        
    allowed = ['b','i','u','br']
        
    matches = re.findall("<(.*?)>", value)
    
    for match in matches:
        tag = match.replace("/","")
        if tag not in allowed:
            value = value.replace( "<%s>" % match, "" )
    
   
  
    # Not try and validate the result.
    try:minidom.parseString( "<xml>%s</xml>" % value )
    except ExpatError:
        value = value.replace("<", "&lt;").replace(">","&gt;")
        value = "<font color='green'>%s</font>" % value
        
    return value
        
    
        
        
        
        
        
        
        
        
        
    # Verify it's valid HTML, if not we return a quoted string (TODO: Should this return an error?)
    #try:
        #minidom.parseString( "<html>" + value  + "</html>")
    #except ExpatError:
        #value = value.replace("<", "&lt;").replace(">","&gt;")
        #value = "<font color='green'>%s</font>" % value
        #return value
        
    # HACK - Should implemented with a proper XML Parser, not regular expressions       
    #value = replaceTag( value, "table", "blockTable" )
    #value = replaceTag( value, "th", "td" )    
    
    value = re.sub("<.*?>", "", value )
    
    #value = removeTag( value, "table" )
    #value = removeTag( value, "td" )
    #value = removeTag( value, "th" )
    #value = removeTag( value, "caption" )
    
    #value = removeTag(  value, "div" )
    #value = removeTag( value, "ul" )
    #value = removeTag( value, "li" )
    #value = removeTag( value, "ol" )
    #value = removeTag( value, "p" )
    
    
    
    return value
    
    
    
    